﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using SocketChat.Core.Sockets;
using SocketChat.Core.WinForm;
using System.Net.Sockets;

namespace SocketChat.Server
{
    public partial class MainForm : Form
    {
        private IPEndPoint _LocalEndPoint;
        private SocketServer _TcpSocketServer;
        //private DateTime _LastLogTime;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="localEndPoint">服务器本地终结点</param>
        public MainForm(IPEndPoint localEndPoint) {
            InitializeComponent();

            _LocalEndPoint = localEndPoint;
        }

        /// <summary>
        /// 窗体载入函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e) {
            _TcpSocketServer = new SocketServer();
            _TcpSocketServer.AddMsgAction = new Action<ListBoxItem>((item) => { this.lbMsg.AddMsg(item); });
            _TcpSocketServer.BindAndListen(_LocalEndPoint, 4);
            _TcpSocketServer.OnlineClients.ListChanged += (obj, args) =>
            {
                this.lbUser.Invoke(new Action(() =>
                {
                    this.lbUser.Items.Clear();
                    this.lbUser.Items.AddRange(_TcpSocketServer.OnlineClients.Select(c => c.DisplayName).ToArray());
                }));
            };
            this.txtIP.Text = _LocalEndPoint.Address.ToString();
            this.txtPort.Text = _LocalEndPoint.Port.ToString();
            //this.lbUser.DataBindings.Add("DataSource", _TcpSocketServer, "ClientList");
        }

        //private void AddClient(string Name) {
        //    this.lbUser.Items.Add(Name);
        //}

        //private void RemoveClient(string Name) {
        //    this.lbUser.Items.Remove(Name);
        //}

        private void btnCopyIP_Click(object sender, EventArgs e) {
            //_TcpSocketServer.OnLineClientList.Add(new Client(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { HeartBeatTime = DateTime.Now, Name = "aaa" });
            Clipboard.SetDataObject(this.txtIP.Text);
        }

        private void btnCopyPort_Click(object sender, EventArgs e) {
            Clipboard.SetDataObject(this.txtPort.Text);
        }
    }
}
